<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI选股系统 - 数据导入</title>
    <script src="/static/lib/js/vue.global.js"></script>
    <script src="/static/lib/js/axios.min.js"></script>
    <link href="/static/lib/css/all.min.css" rel="stylesheet">
    <link href="/static/base.css" rel="stylesheet">
    <link href="/static/components.css" rel="stylesheet">
    <link href="/static/pages.css" rel="stylesheet">
    <link href="/static/utilities.css" rel="stylesheet">
    <link href="/static/optimized-table-styles.css" rel="stylesheet">
    <link href="/static/admin/admin.css" rel="stylesheet">
</head>
<body>
  <div id="app" class="admin-layout">
    <!-- 顶部导航 -->
    <div class="admin-header">
      <h2>选择导入</h2>
      <div>
        <button class="btn" onclick="location.href='/'">返回前台</button>
        <button class="btn" onclick="logout()">退出</button>
      </div>
    </div>

    <!-- 主体内容 -->
    <div class="admin-main">
      <!-- 左侧导航（公共组件注入） -->
      <div class="admin-sidebar"></div>

      <!-- 右侧内容区域 -->
      <div class="admin-content">
        <div class="content-page active">
          <h3>选择导入</h3>
          <p class="page-description">支持导入hsnapshot、block、blockinfo、fboard、stock、label等数据文件</p>

            <div class="content-grid">
                <!-- 左侧：导入配置面板 -->
                <div class="content-card">
                    <h4><i class="fas fa-cog"></i> 导入配置</h4>
                    
                    <div class="form-group">
                        <label class="form-label">数据文件目录</label>
                        <input type="text" v-model="dataDirectory" class="form-control" placeholder="请输入数据文件存放目录路径">
                        <div class="form-help">
                            <i class="fas fa-info-circle"></i>
                            例如: /path/to/data 或 C:\data
                        </div>
                    </div>
                    
                    <div class="directory-info" v-if="dataDirectory" style="margin: 12px 0; padding: 8px; background: #f8f9fa; border-radius: 4px;">
                        <strong>当前目录:</strong> {{ dataDirectory }}
                    </div>
                    
                    <button @click="refreshFiles" class="btn btn-primary" :disabled="!dataDirectory || loading">
                        <i v-if="loading" class="fas fa-spinner fa-spin"></i>
                        <i v-else class="fas fa-sync-alt"></i>
                        {{ loading ? '加载中...' : '刷新文件列表' }}
                    </button>
                </div>

                <!-- 右侧：结果展示区域 -->
                <div class="content-card" style="grid-column: 2 / -1;">
                        <div v-if="loading" class="loading">
                            <i class="fas fa-spinner fa-spin"></i> 正在加载文件列表...
                        </div>
                        
                                                 <div v-else-if="!loading && files && files.length > 0">
                            <!-- 成功提示消息 -->
                            <div v-if="importSuccessMessage" class="alert alert-success" style="margin-bottom: 20px; display: flex; justify-content: space-between; align-items: center;">
                                <div>
                                    <i class="fas fa-check-circle"></i>
                                    {{ importSuccessMessage }}
                                </div>
                                <button @click="clearSuccessMessage" class="btn btn-sm btn-outline-success" style="margin-left: 10px;">
                                    <i class="fas fa-times"></i>
                                </button>
                            </div>
                            
                            <!-- 文件列表表格 -->
                            <div class="table-container performance-table-container">
                                <table class="performance-table">
                                    <thead>
                                        <tr>
                                            <th>交易日期</th>
                                            <th>文件名</th>
                                            <th>文件类型</th>
                                            <th>文件大小</th>
                                            <th>操作</th>
                                            <th>导入条数</th>
                                        </tr>
                                    </thead>
                                                                         <tbody>
                                                                                 <tr v-for="file in files" :key="file.filename">
                                            <td><span class="trade-date">{{ formatTradeDate(extractTradeDate(file.filename)) || '未知日期' }}</span></td>
                                            <td>{{ file.filename }}</td>
                                            <td><span class="file-type-badge">{{ getFileTypeName(file.filename) }}</span></td>
                                            <td><span class="file-size">{{ file.size_mb }} MB</span></td>
                                             <td>
                                                 <button @click="processImport(file)" 
                                                         class="btn btn-sm"
                                                         :class="{
                                                             'btn-success': !file.importing && file.import_status !== 'success',
                                                             'btn-secondary': file.importing || file.import_status === 'success',
                                                             'btn-danger': file.import_status === 'error'
                                                         }"
                                                         :disabled="file.importing || file.import_status === 'success'">
                                                     <i v-if="file.importing" class="fas fa-spinner fa-spin"></i>
                                                     <i v-else-if="file.import_status === 'success'" class="fas fa-check"></i>
                                                     <i v-else-if="file.import_status === 'error'" class="fas fa-times"></i>
                                                     <i v-else class="fas fa-download"></i>
                                                     {{ file.importing ? '导入中...' : 
                                                        file.import_status === 'success' ? '已导入' : 
                                                        file.import_status === 'error' ? '导入失败' : '导入' }}
                                                 </button>
                                             </td>
                                             <td>
                                                 <span v-if="file.import_status" 
                                                       class="import-count"
                                                       :class="'status-' + file.import_status"
                                                       :title="file.import_message">
                                                     {{ file.import_status === 'success' ? (file.import_count + ' 条') : 
                                                        file.import_status === 'warning' ? (file.import_count + ' 条') : 
                                                        file.import_status === 'error' ? '0 条' : '' }}
                                                 </span>
                                                 <span v-else class="import-count status-pending">-</span>
                                             </td>
                                         </tr>
                                     </tbody>
                                </table>
                            </div>
                        </div>
                        
                                                 <div v-else-if="!loading && (!files || files.length === 0)" class="empty-state">
                            <div><i class="fas fa-folder-open"></i></div>
                            <div>目录中没有找到可导入的文件</div>
                            <div>请检查目录路径是否正确</div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
      </div>
    </div>
  </div>
    
    <script src="/static/admin/components/sidebar.js"></script>
    <script>
        // JavaScript部分保持不变
        const { createApp } = Vue;
        
        createApp({
                                                          data() {
                    return {
                        dataDirectory: './data', // 默认设置为当前data目录
                        files: [], // 文件列表
                        loading: true, // 初始化为true，避免在数据加载前渲染
                        importSuccessMessage: '', // 导入成功提示消息

                    }
                },
            
            async mounted() {
                // 尝试从localStorage恢复上次使用的目录，如果没有则使用默认目录
                const savedDir = localStorage.getItem('dataDirectory');
                if (savedDir) {
                    this.dataDirectory = savedDir;
                }
                

                
                // 自动加载文件列表
                try {
                    await this.refreshFiles();
                } catch (error) {
                    console.error('mounted中refreshFiles失败:', error);
                    this.loading = false;
                }
            },
            
            methods: {
                                 async refreshFiles() {
                     if (!this.dataDirectory) {
                         console.error('请先设置数据文件目录');
                         return;
                     }
                    
                    this.loading = true;
                    try {
                        const response = await axios.get('/api/import/files', {
                            params: { directory: this.dataDirectory }
                        });
                        
                                                 if (response.data.success) {
                             const rawFiles = response.data.data.files || [];
                             
                             // 直接处理文件列表，不按日期分组
                             this.files = rawFiles.map(file => ({
                                 filename: file.name,
                                 size_mb: (file.size / (1024 * 1024)).toFixed(2),
                                 modified_time: file.date,
                                 type: file.type,
                                 path: file.path
                             })).sort((a, b) => {
                                 // 按文件名排序（通常包含日期）
                                 return b.filename.localeCompare(a.filename);
                             });
                             
                             
                             // 保存目录到localStorage
                             localStorage.setItem('dataDirectory', this.dataDirectory);
                                                 } else {
                             console.error('API返回错误:', response.data.error);
                         }
                     } catch (error) {
                         console.error('加载文件列表失败:', error);
                         // 确保在错误情况下也设置loading为false
                         this.loading = false;
                    } finally {
                        this.loading = false;
                    }
                },
                
                async processImport(file) {
                    // 设置导入状态
                    file.importing = true;
                    file.import_status = '';
                    file.import_message = '';
                    file.import_count = 0;
                    
                    try {
                        const response = await axios.post('/api/import/process', {
                            files: [{
                                name: file.filename,
                                path: file.path,
                                type: file.type
                            }]
                        });
                        
                        if (response.data.success) {
                            const processedFiles = response.data.data.processed_files;
                            if (!processedFiles || processedFiles.length === 0) {
                                console.error('导入失败: 没有返回处理结果');
                                file.import_status = 'error';
                                file.import_message = '导入失败: 没有返回处理结果';
                                file.import_count = 0;
                                return;
                            }
                            
                            const result = processedFiles[0];
                            
                            // 设置导入状态
                            file.import_status = result.status;
                            file.import_message = result.message;
                            
                            // 提取导入条数
                            if (result.message && result.status === 'success') {
                                const match = result.message.match(/共 (\d+) 条记录/);
                                file.import_count = match ? parseInt(match[1]) : 0;
                            } else if (result.status === 'warning') {
                                const match = result.message.match(/共 (\d+) 条记录/);
                                file.import_count = match ? parseInt(match[1]) : 0;
                            } else {
                                file.import_count = 0;
                            }
                            
                            // 导入成功后，不刷新页面，只更新当前文件状态
                            if (result.status === 'success') {
                                this.importSuccessMessage = `文件 "${file.filename}" 导入成功，共导入 ${file.import_count} 条记录`;
                                // 3秒后自动清除成功消息
                                setTimeout(() => {
                                    this.importSuccessMessage = '';
                                }, 3000);
                            }
                            // 移除自动刷新逻辑
                        } else {
                            console.error('导入失败:', response.data.error);
                            file.import_status = 'error';
                            file.import_message = response.data.error;
                            file.import_count = 0;
                        }
                    } catch (error) {
                        console.error('导入失败:', error.message);
                        file.import_status = 'error';
                        file.import_message = error.message;
                        file.import_count = 0;
                    } finally {
                        file.importing = false;
                    }
                },
                
                getFileTypeName(filename) {
                    const filenameLower = filename.toLowerCase();
                    
                    if (filenameLower.indexOf('hsnapshot') !== -1 || filenameLower.startsWith('hs_')) {
                        return '股票快照';
                    } else if (filenameLower === 'block.csv' || filenameLower.indexOf('block_') !== -1) {
                        return '板块信息';
                    } else if (filenameLower === 'blockinfo.csv' || filenameLower.indexOf('blockinfo_') !== -1) {
                        return '板块关联';
                    } else if (filenameLower.indexOf('fboard') !== -1 || filenameLower.startsWith('fb_')) {
                        return '涨停分析';
                    } else if (filenameLower.indexOf('stock') !== -1 || filenameLower.startsWith('stock_')) {
                        return '股票信息';
                    } else if (filenameLower.indexOf('label') !== -1 || filenameLower.startsWith('label_')) {
                        return '标签信息';
                    } else if (filenameLower.indexOf('snapshot') !== -1 || filenameLower.indexOf('kline') !== -1 || filenameLower.indexOf('daily') !== -1) {
                        return '股票快照';
                    } else if (filenameLower.indexOf('sector') !== -1 || filenameLower.indexOf('industry') !== -1) {
                        return '板块信息';
                    } else {
                        return '未知类型';
                    }
                },
               
                extractTradeDate(filename) {
                    // 从文件名中提取日期，支持多种格式
                    const patterns = [
                        /(\d{4})(\d{2})(\d{2})/, // YYYYMMDD
                        /(\d{4})-(\d{2})-(\d{2})/, // YYYY-MM-DD
                        /(\d{4})_(\d{2})_(\d{2})/ // YYYY_MM_DD
                    ];
                    
                    for (const pattern of patterns) {
                        const match = filename.match(pattern);
                        if (match) {
                            return match[1] + match[2] + match[3]; // 返回YYYYMMDD格式
                        }
                    }
                    
                    return null;
                },
                
                formatTradeDate(dateStr) {
                    if (!dateStr || typeof dateStr !== 'string' || dateStr.length < 8) return '未知日期';
                    // 将YYYYMMDD格式转换为YYYY-MM-DD格式
                    const year = dateStr.substring(0, 4);
                    const month = dateStr.substring(4, 6);
                    const day = dateStr.substring(6, 8);
                    return `${year}-${month}-${day}`;
                },
                
                clearSuccessMessage() {
                    this.importSuccessMessage = '';
                },
                

                
                
            }
        }).mount('#app');
        // 注入公共侧边栏
        injectAdminSidebar('/admin/imps');
        
        // 退出登录
        async function logout(){
            try{ 
                await fetch('/admin/logout', {method:'POST'}); 
                location.href='/admin/login'; 
            }catch(e){ 
                location.href='/admin/login'; 
            }
        }
    </script>
</body>
</html>
